#-*-coding:utf-8-*-

from improgrammer.programmer.models import *
from improgrammer.programmer.forms import *

from django.shortcuts import render_to_response
from django.http import HttpRequest
from django.http import HttpResponse
from django.http import HttpResponseRedirect

from django.core.paginator import Paginator, InvalidPage, EmptyPage

from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login

# Create your views here.

def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            if form.cleaned_data['password'] == form.cleaned_data['password_confirm']:
                user = User(username = form.cleaned_data['username'], password = form.cleaned_data['password'], email = form.cleaned_data['email'])
                user.save()
                return HttpResponseRedirect('/')
            else:
                form.errors['password'] = 'not same'
    else:
        form = RegisterForm()
        
    return render_to_response('register.html', {'form':form})

def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid:
            user = authenticate(username = form.cleaned_data['username'], password = form.cleaned_data['password'])
            if user is not None:
                login(request, user)
                return HttpResponseRedirect('/')
            else:
                return render_to_response('message.html', {'code':101})
    else:
        form = LoginForm()

    return render_to_response('login.html', {'form' : form})

def home(request):
    return render_to_response('home.html')
